package com.pany.rememberpass;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @name： RememberPass
 * @author： zs
 * @time： 2022/5/13 0013
 */
public class NetUtils2 {

    //    public static String base_url = "https://www.yiketianqi.com/free/day";
    public static String base_url = "https://www.yiketianqi.com/free/day?appid=94383875&appsecret=ub72Rqjq&city=";
    public static String appid3 = "94383875y";
    public static String appid = "36646344";
    public static String appsecret3 = "3zp4hOsw";
    public static String appsecret = "c11gQbp9";

    public static String getWeatherOfCity(String city) {
//        String rul = base_url + "?" + "appid=" + appid + "&" + "appsecret=" + appsecret + "&" + "city=" + city;
        String rul = base_url + city;

        Log.d(rul, "getWeatherOfCity:  rul ====== " + rul);

        return decode(doGet(rul));
    }

    public static String decode(String unicodeStr) {
        if (unicodeStr == null) {
            return null;
        }
        StringBuffer retBuf = new StringBuffer();
        int maxLoop = unicodeStr.length();
        for (int i = 0; i < maxLoop; i++) {
            if (unicodeStr.charAt(i) == '\\') {
                if ((i < maxLoop - 5) && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr.charAt(i + 1) == 'U')))
                    try {
                        retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));
                        i += 5;
                    } catch (NumberFormatException localNumberFormatException) {
                        retBuf.append(unicodeStr.charAt(i));
                    }
                else
                    retBuf.append(unicodeStr.charAt(i));
            } else {
                retBuf.append(unicodeStr.charAt(i));
            }
        }
        return retBuf.toString();
    }

    public static String doGet(String rul) {
        String resultJSONString = "";
        BufferedReader bufferedReader = null;
        try {
            // 1.建立链接
            HttpURLConnection httpURLConnection = null;

            URL requestRrl = new URL(rul);
            httpURLConnection = (HttpURLConnection) requestRrl.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.connect();

            //.2.获取二进制流
            InputStream inputStream = httpURLConnection.getInputStream();
            //3.将二进制流 包装
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            // 4.从 bufferread中读取字符串
            String line = "";
            StringBuffer stringBuffer = new StringBuffer();

            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
            if (stringBuffer.length() == 0) {
                return null;
            }
            resultJSONString = stringBuffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return resultJSONString;
    }

    public static boolean doPost(String strUrl) {

        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        boolean reuslt = false;

        //1.打开链接
        try {
            URL url = new URL(strUrl);
            connection = (HttpURLConnection) url.openConnection();
            //2. 准备数据
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("userName", "zhang");
            paramMap.put("pass", "123");
            String paramData = paramDataString(paramMap);
//3. 设置连接信息 ,信息的长度
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(10000);
            connection.setRequestProperty("Contetn_Length", String.valueOf(paramData.length()));
            //3.1.设置connect可以像服务器端写
            connection.setDoOutput(true);
            //4.获取输出流,输出信息
            outputStream = connection.getOutputStream();
            outputStream.write(paramData.getBytes());
//5.获取服务的响应结果
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                reuslt = true;
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return reuslt;
    }

    private static String paramDataString(Map<String, String> paramData) {

        StringBuffer stringBuffer = new StringBuffer();

        Set<Map.Entry<String, String>> entries = paramData.entrySet();

        for (Map.Entry<String, String> entry : entries) {

            try {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                        .append("&");

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        stringBuffer.deleteCharAt(stringBuffer.length() - 1);

        return stringBuffer.toString();
    }

}
